package com.yt.base.controller.order;

import com.yt.base.controller.core.BaseController;
import com.yt.base.controller.order.vo.OOrderInfoVo;
import com.yt.base.util.BarCodePrintUtil;
import com.yt.base.util.ExcelOpareUtil;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.order.api.interfaces.*;
import com.yt.order.api.model.*;
import com.yt.order.api.utils.OrderConstants;
import com.yt.util.DateUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/order/order")
public class OrderController extends BaseController {

	@Autowired
	private ProductTypeService productTypeService;
	@Autowired
	private ProductService productService;
	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private InstitutionService institutionService;
	@Autowired
	private OrderNumberService orderNumberService;
	@Autowired
	private ReservationService reservationService;
	@Autowired
	private GroupOrderService groupOrderService;
	@Autowired
	private GroupOrderProductService groupOrderProductService;
	@Autowired
	private OrderNumberService oOrderNumberService;

	private final static Logger logger = LoggerFactory.getLogger(OrderController.class);


	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(value = "orderNo", required = false) String orderNo,
							 @RequestParam(value = "mobile", required = false) String mobile,
							 @RequestParam(value = "cardNumber", required = false) String cardNumber,
							 @RequestParam(value = "endUser", required = false) String endUser,
							 @RequestParam(value = "buyUser", required = false) String buyUser,
							 @RequestParam(value = "startDate", required = false) String startDate,
							 @RequestParam(value = "endDate", required = false) String endDate,
							 @RequestParam(value = "groupOrderId", required = false) Long groupOrderId,
							 @RequestParam(value = "isExport", required = false) String isExport,
							 HttpServletRequest request,
							 HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("order/order/OrderList");
		try {
			QueryFilter filter = new DynamicSQLFilterImpl();
			filter.addFilter(request.getParameterMap());

//			filter.setSortField("id", true);
			if (StringUtils.isNotEmpty(orderNo)) {
				filter.addFilter("Q_orderNo_S_LK", orderNo.trim());
				mav.addObject("orderNo", orderNo);
			}
			if (StringUtils.isNotEmpty(mobile)) {
				filter.addFilter("Q_mobile_S_LK", mobile.trim());
				mav.addObject("mobile", mobile);
			}
			if (StringUtils.isNotEmpty(cardNumber)) {
				filter.addFilter("Q_cardNumber_S_LK", cardNumber.trim());
				mav.addObject("cardNo", cardNumber);
			}
			if (groupOrderId != null && groupOrderId > 0) {
				filter.addFilter("Q_groupOrderId_L_EQ", groupOrderId + "");
				mav.addObject("groupOrderId", groupOrderId);
			}

			if (StringUtils.isNotEmpty(buyUser)) {
				filter.addFilter("Q_buyUser_S_LK", buyUser.trim());
				mav.addObject("buyUser", buyUser);
			}
			if (StringUtils.isNotEmpty(endUser)) {
				filter.addFilter("Q_endUser_S_LK", endUser.trim());
				mav.addObject("endUser", endUser);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			if (StringUtils.isNotEmpty(startDate)) {
				filter.addFilter("Q_startDate_L_GE", sdf.parse(startDate).getTime() + "");
				mav.addObject("startDate", startDate);
			}
			if (StringUtils.isNotEmpty(endDate)) {
				filter.addFilter("Q_endDate_L_LE", sdf.parse(endDate).getTime() + "");
				mav.addObject("endDate", endDate);
			}
			filter.addFilter("Q_orderStatus_N_NEQ", OrderConstants.OrderStatus.Disabled.getStatusValue());
			filter.setSortField("orderTime desc,id ", false);
			List<OrderInfo> list = orderInfoService.find(filter);

			if (isExport != null) {
				exportOrder(list, request, response);
				return null;
			}
			int count = orderInfoService.count(filter);

			Calendar c1 = Calendar.getInstance();
			Calendar c2 = Calendar.getInstance();
			Calendar c0 = Calendar.getInstance();
			c0.set(Calendar.HOUR, 0);
			c0.set(Calendar.MINUTE, 0);
			c0.set(Calendar.SECOND, 0);
			List<OOrderInfoVo> voList = new ArrayList<OOrderInfoVo>();
			OOrderInfoVo vo = null;
			for (OrderInfo bean : list) {
				vo = new OOrderInfoVo();
				try {
					BeanUtils.copyProperties(vo, bean);
				} catch (Exception ex) {
				}

				if (bean.getStartDate() != null) {
					c1.setTimeInMillis(bean.getStartDate()*1000);
				} else if (bean.getOrderTime() != null) {
					c1.setTimeInMillis(bean.getOrderTime()*1000);
				}
				if (bean.getEndDate() != null) {
					c2.setTimeInMillis(bean.getEndDate()*1000);
				} else {
					c2.setTimeInMillis(bean.getOrderTime()*1000);
					c2.add(Calendar.MONTH, 6);
					c2.set(Calendar.HOUR, 0);
					c2.set(Calendar.MINUTE, 0);
					c2.set(Calendar.SECOND, 1);
				}
				vo.setStartDateStr(DateUtils.formatDate(c1.getTime()));
				vo.setEndDateStr(DateUtils.formatDate(c2.getTime()));
				vo.setOrderTimeStr(DateUtils.formatDateTime(new Date(bean.getOrderTime()*1000)));

				vo.setExpired(c2.after(c0) ? "N" : "Y");
				voList.add(vo);
			}

			//团体订单
			QueryFilter groupFilter = new DynamicSQLFilterImpl();
			groupFilter.setSortField("id", true);
			groupFilter.setPagingBean(null);
			List<GroupOrder> groupOrderList = groupOrderService.find(groupFilter);
			mav.addObject("groupOrderList", groupOrderList);
			mav.addObject("total", count);
			mav.addObject("list", voList);
			mav.addObject("start", filter.getPagingBean().getStart());
			mav.addObject("limit", filter.getPagingBean().getPageSize());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return mav;
	}

	@RequestMapping("/save")
	@ResponseBody
	public Object save(OrderInfo orderInfo, @RequestParam(value = "idInstitution",required = true)Long idInstitution, @RequestParam(value = "idProduct",required = true)Long idProduct) {
		MsgBean msg = new MsgBean();
		try {
			orderInfo.setIdInstitution(idInstitution);
			orderInfo.setIdProduct(idProduct);
			if (StringUtils.isNotEmpty(orderInfo.getBuyUser())) {
				orderInfo.setBuyUser(orderInfo.getBuyUser().replace(" ", ""));
			}
			if (StringUtils.isNotEmpty(orderInfo.getEndUser())) {
				orderInfo.setEndUser(orderInfo.getEndUser().replace(" ", ""));
			}
			if (orderInfo.getPay() == null) {
				orderInfo.setPay(0);
			}
			OrderInfo ob = null;
			if (orderInfo.getId() != null && orderInfo.getId() != 0) {
				ob = orderInfoService.get(orderInfo.getId());
			} else {
				ob = new OrderInfo();
				// 设置订单号
				ob.setOrderNo(oOrderNumberService.nextOrderNumber(OrderConstants.OrderFrom.INTERNAL.getValue(), OrderConstants.OrderType.Single.getType()));
				ob.setOrderType("个人");
				// 不加项
				Date startDate = new Date();
				Calendar c1 = Calendar.getInstance();
				c1.setTime(startDate);
				c1.add(Calendar.MONTH, 6);
				ob.setStartDate(startDate.getTime());
				ob.setIsPost("0");
			}
			if (orderInfo.getIdInstitution() != null) {
				Institution institution = institutionService.get(orderInfo.getIdInstitution());
				ob.setInstitutionName(institution.getName());
				ob.setIdInstitution(institution.getId());
			} else {
				ob.setInstitutionName(orderInfo.getInstitutionName());
			}
			if (orderInfo.getIdProduct() != null) {
				Product product = productService.get(orderInfo.getIdProduct());
				ob.setIdProduct(product.getId());
				ob.setProductName(product.getName());
				ob.setBasePrice(product.getBasePrice());
				ob.setProductPrice(product.getSalePrice());
			} else {
				ob.setProductName(orderInfo.getProductName());
			}
			ob.setSalePrice(orderInfo.getSalePrice());
			ob.setBuyUser(orderInfo.getBuyUser());
			ob.setEndUser(orderInfo.getEndUser());
			ob.setAge(orderInfo.getAge());
			ob.setSex(orderInfo.getSex());
			ob.setPhone(orderInfo.getPhone());
			ob.setMobile(orderInfo.getMobile());
			ob.setAddress(orderInfo.getAddress());
			ob.setPostcode(orderInfo.getPostcode());
			ob.setEmail(orderInfo.getEmail());
			ob.setReportType(orderInfo.getReportType());
			ob.setIdCard(orderInfo.getIdCard());
			ob.setOrderFrom(orderInfo.getOrderFrom());
			ob.setOrderTime(orderInfo.getOrderTime());

			ob.setComment(orderInfo.getComment().replaceAll("[\n\r]", ""));

			ob.setOrderStatus(OrderConstants.OrderStatus.NewOrder.getStatusValue());
			ob.setModifyDate(System.currentTimeMillis());

			if (orderInfo.getId() != null) {
				orderInfoService.update(ob);
			} else {
				orderInfoService.insert(ob);
			}
			// 如果合作商家的属性中，自动预约属性为1， 则添加订单的同时自动增加预约记录
//		Reservation reservation = reservationService.getReservationByOrderId(ob.getId());
//		if (ob.getInstitution() != null) {
//			if ("1".equals(ob.getInstitution().getAutoReserve())) {
//				if (ob.getProduct().getId() != orderInfo.getProduct().getId() || reservation == null) {
//					if (reservation != null) {
//						reservationService.updateReservationStatus(reservation.getId(), OrderConstants.ReservationStatus.Canceled.value);
//					}
//					reservationService.addReservationByOrder(ob);
//					ob.setBespeaked("1");
//					orderInfoService.save(ob);
//				}
//			} else {
//				if (reservation != null) {
//					reservationService.updateReservationStatus(reservation.getId(), OrderConstants.ReservationStatus.Canceled.value);
//				}
//			}
//		}
		} catch (Exception ex) {
			msg.failure("保存异常，请重试！");
			logger.error("保存订单异常,", ex);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/multiDel")
	@ResponseBody
	public Object multiDel(@RequestParam(value = "ids", required = true) String ids) {
		MsgBean msg = new MsgBean();
		try {
			String[] idArr = ids.split(",");
			OrderInfo orderInfo = null;
			for (int i = 0; i < idArr.length; i++) {
				orderInfo = orderInfoService.get(Long.parseLong(idArr[i]));
				orderInfo.setOrderStatus(OrderConstants.OrderStatus.Disabled.getStatusValue());
				orderInfoService.update(orderInfo);
			}
		} catch (Exception ex) {
			logger.error("删除订单出错，", ex);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/get")
	@ResponseBody
	public Object get(@RequestParam(value = "id", required = true) Long id) {
		MsgBean msg = new MsgBean();
		OrderInfo orderInfo = orderInfoService.get(id);
		msg.put("data", orderInfo);
		return msg.returnMsg();
	}

	@RequestMapping("/changeStatus")
	@ResponseBody
	public Object changeStatus(@RequestParam(value = "ids", required = true) String ids,
								 @RequestParam(value = "status", required = true) String status,
								 @RequestParam(value = "field", required = true) String field
	) {
		MsgBean msg = new MsgBean();
		String[] idArr = ids.split(",");
		OrderInfo orderInfo = null;
		for (int i = 0; i < idArr.length; i++) {
			orderInfo = orderInfoService.get(Long.parseLong(idArr[i]));
			if ("isChecked".equals(field)) {
				orderInfo.setIsChecked(status);
				//addLog("修改到检", orderInfo.toString(), "OrderInfo");
			} else if ("reportStatus".equals(field)) {
				orderInfo.setReportStatus(status);
				orderInfo.setIsChecked(status);
				//addLog("修改报告状态", orderInfo.toString(), "OrderInfo");
			} else if ("paidToInstitution".equals(field)) {
				orderInfo.setPaidToInstitution(status);
				//addLog("修改付款给商家", orderInfo.toString(), "OrderInfo");
			} else if ("orderState".equals(field)) {
				orderInfo.setOrderStatus(status);
				//addLog("修改订单状态", orderInfo.toString(), "OrderInfo");
			}
			orderInfoService.update(orderInfo);
		}
		return msg.returnMsg();
	}

	public void export(List<OrderInfo> list, HttpServletRequest request, HttpServletResponse response) {
		List<String> title = new ArrayList<String>();
		title.add("订单编号");
		title.add("购买人");
		title.add("使用人");
		title.add("性别");
		title.add("年龄");
		title.add("手机");
		title.add("电话");
		title.add("地址");
		title.add("合作商家");
		title.add("产品名称");
		title.add("产品价格");
		title.add("成交价格");
		title.add("备注");
		title.add("是否已付款给商家");
		title.add("是否到检");
		title.add("报告已回");
		title.add("报告领取方式");
		title.add("订单时间");
		List<List> excelList = new ArrayList<List>();
		if (list.size() > 0) {
			for (OrderInfo ob : list) {
				if (Long.parseLong(ob.getOrderStatus()) == -1) {
					continue;
				}
				List<String> strlist = new ArrayList<String>();
				strlist.add(ob.getOrderNo());
				strlist.add(ob.getBuyUser());
				strlist.add(ob.getEndUser());
				strlist.add(ob.getSex());
				strlist.add((ob.getAge() != null ? ob.getAge().toString() : ""));
				strlist.add(ob.getMobile());
				strlist.add(ob.getPhone());
				strlist.add(ob.getAddress());
				strlist.add(ob.getInstitutionName() != null ? ob.getInstitutionName() : "");
				strlist.add(ob.getProductName() != null ? ob.getProductName() : "");
				strlist.add((ob.getProductPrice() != null ? ob.getProductPrice().toString() : "0"));
				strlist.add((ob.getSalePrice() != null ? ob.getSalePrice().toString() : "0"));
				strlist.add(ob.getComment());
				strlist.add(ob.getPaidToInstitution() == null || "0".equals(ob.getPaidToInstitution()) ? "否" : "是");
				strlist.add(ob.getIsChecked() != null && ob.getIsChecked().equals("1") ? "是" : "否");
				strlist.add(ob.getReportStatus() != null && ob.getReportStatus().equals("1") ? "是" : "否");
				strlist.add(ob.getReportType());
				strlist.add(DateUtils.formatDate(new Date(ob.getOrderTime()*1000)));
				excelList.add(strlist);
			}
		}

		response.reset();
		response.setContentType("application/vnd.ms-excel");

		response.setHeader("Content-Disposition", "attachment;Filename=Data(" + DateUtils.formatDate(new Date(System.currentTimeMillis())) + ").xls");

		try {
			ExcelOpareUtil.write(response.getOutputStream(), title, excelList);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
//
//	@RequestMapping("/getOrderDetail")
//	public ModelAndView getOrderDetail(@RequestParam(value = "id", required = true) Long id) {
//		ModelAndView mav = new ModelAndView("order/order/OrderDetail.jsp");
//		OrderInfo orderInfo = orderInfoService.get(id);
//		List<Reservation> reservationList = reservationService.findByOrderId(id);
////		invoiceList = invoiceService.getInvoiceByOrderId(id);
////		postOrderList = postOrderService.getPostOrderByOrderId(id);
//		mav.addObject("orderInfo", orderInfo);
//		mav.addObject("reservationList", reservationList);
//		return mav;
//	}


	public static int getAge(String id) {
//		Date date = new Date();
		int born = 0;
		if (id.length() == 15) {
			born = 1900 + (new Long(id.substring(6, 8))).intValue();
		} else if (id.length() == 18) {
			born = (new Long(id.substring(6, 10))).intValue();
		}
		return 2015 - born;

	}
	@RequestMapping("/toPrintBarcode")
	public ModelAndView toPrintBarcode(@RequestParam(value = "ids", required = false) String ids,
									   @RequestParam(value = "groupOrderId", required = false) String groupOrderId){
		ModelAndView mav = new ModelAndView("order/printbarcode");
		return mav;
	}
	@RequestMapping("/printBarcodeOf")
	public void printBarcodeOf(@RequestParam(value = "ids", required = false) String ids,
							   @RequestParam(value = "groupOrderId", required = false) String groupOrderId,
							   @RequestParam(value = "template", required = true) String template,
							   HttpServletRequest request,
							   HttpServletResponse response
	) {
		List<OrderInfo> orderList = null;
		if (StringUtils.isNotEmpty(groupOrderId)) {
			orderList = orderInfoService.getGroupOrderList(Long.parseLong(groupOrderId));
		} else if (StringUtils.isNotEmpty(ids)) {
			String[] idArr = ids.split(",");
			orderList = new ArrayList<OrderInfo>();
			for (String id : idArr) {
				orderList.add(orderInfoService.get(Long.parseLong(id)));
			}
		}
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		Calendar ca = Calendar.getInstance();
		String orderValidFrom = null;
		String orderValidTo = null;
		HashMap<String, Object> singleData = null;
		for (OrderInfo order : orderList) {
			if (order.getStartDate() != null) {
				orderValidFrom = DateUtils.formatDate(new Date(order.getStartDate()*1000));
			} else {
				ca.setTimeInMillis(order.getOrderTime()*1000);
				orderValidFrom = DateUtils.formatDate(ca.getTime());
			}
			if (order.getEndDate() != null) {
				orderValidTo = DateUtils.formatDate(new Date(order.getEndDate()*1000));
			} else {
				ca.setTimeInMillis(order.getOrderTime()*1000);
				ca.add(Calendar.MONTH, 6);
				orderValidTo = DateUtils.formatDate(ca.getTime());
			}
			Product product = null;
			if (order.getIdProduct() != null) {
				product = productService.get(order.getIdProduct());
			}
			singleData = new HashMap<String, Object>();
			singleData.put("title", order.getInstitutionName() != null ? order.getInstitutionName() : "");
			singleData.put("name", order.getEndUser());
			singleData.put("sex", order.getSex());
			singleData.put("age", order.getAge());
			singleData.put("product", product != null ? product.getName() : order.getProductName());
			singleData.put("report", (StringUtils.isEmpty(order.getReportType()) ? "自取" : order.getReportType()));
			singleData.put("expire", orderValidFrom + "至" + orderValidTo);
			singleData.put("validFrom", orderValidFrom);
			singleData.put("validTo", orderValidTo);
			singleData.put("barcode", order.getOrderNo());
			singleData.put("tuan", order.getCompany() != null && !"".equals(order.getCompany()) ? order.getCompany() : null);
			singleData.put("service", product != null ? product.getService() : null);
			data.add(singleData);
		}
		(new BarCodePrintUtil()).print(data, template, request, response);
	}
//	// 出卡
//	public String sendCard(@RequestParam(value="id", required = true) String ids) {
//		String[] jgstr = ids.split(";");
//		List<OrderInfo> cardList = new ArrayList<OrderInfo>();
//		OrderInfo order = null;
//		StoreCard card = null;
//		institutionList=institutionService.getStoreInstitutionList();
//		for (int i = 0; i < jgstr.length; i++) {
//			order=orderInfoService.get(Long.parseLong(jgstr[i]));
//			if (order.getProduct() != null) {
//				card=storeCardService.getOne(order.getProduct().getId(), null);
//				if (card != null) {
//					order.setCardNumber(card.getCardNo());
//					order.setCardPassword(card.getPasswd());
//				}
//			}
//			cardList.add(order);
//		}
//		return "card";
//	}

	private void exportOrder(List<OrderInfo> orderList, HttpServletRequest request, HttpServletResponse response) {
		String exportAgent = request.getParameter("agentorderlist");
		List<String> title = new ArrayList<String>();
		title.add("订单来源");
		title.add("购买人");
		title.add("体检人姓名");
		title.add("体检人性别");
		title.add("体检人年龄");
		title.add("电话");
		title.add("手机");
		title.add("地址");
		title.add("商家名称");
		title.add("套餐名称");
		title.add("卡号");
		title.add("市场价格");
		title.add("成交价格");
		title.add("备注");
		title.add("订单时间");
		title.add("报告领取方式");
		title.add("报告已回");
		title.add("是否已预约");
		title.add("已付款给商家");

		List<List> excelList = new ArrayList<List>();
		Invoice invoice = null;
//		OPostOrder postOrder = null;
		if (orderList != null && orderList.size() > 0) {
			for (OrderInfo ob : orderList) {
// inovice = invoiceService.getInvoiceByOrderId(ob.getId());
// postOrder = postOrderService.getPostOrderByOrderId(ob.getId());
				List<String> strlist = new ArrayList<String>();
				strlist.add(ob.getOrderFrom());
				strlist.add(ob.getBuyUser());
				strlist.add(ob.getEndUser());
				strlist.add(ob.getSex());
				strlist.add((ob.getAge() != null ? ob.getAge().toString() : ""));
				strlist.add(ob.getPhone());
				strlist.add(ob.getAddress());
				strlist.add(ob.getMobile());
				strlist.add(ob.getInstitutionName() != null ? ob.getInstitutionName() : "");
				strlist.add(ob.getProductName() != null ? ob.getProductName() : "");
				strlist.add(ob.getCardNumber() != null ? ob.getCardNumber() : "");
				strlist.add(ob.getProductPrice().toString());
				strlist.add(ob.getSalePrice().toString());
				strlist.add(ob.getComment());
				strlist.add(DateUtils.formatDate(new Date(ob.getOrderTime()*1000)));
				strlist.add(ob.getReportType() != null ? ob.getReportType() : "");
				strlist.add((ob.getReportStatus() != null && "1".equals(ob
						.getReportStatus())) ? "是" : "否");
				strlist.add(ob.getBespeaked() != null
						&& "1".equals(ob.getBespeaked()) ? "是" : "否");
				strlist.add(ob.getPaidToInstitution() != null
						&& "1".equals(ob.getPaidToInstitution()) ? "是" : "否");
				excelList.add(strlist);
			}
		}
		response.reset();
		response.setContentType("application/vnd.ms-excel");

		response.setHeader("Content-Disposition", "attachment;Filename=Data("
				+ (new Date()).getTime() + ").xls");

		try {
			ExcelOpareUtil.write(response.getOutputStream(), title, excelList);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/updateCommentOf")
	public String updateCommentOf(@RequestParam(value = "id", required = true) Long id,
								  @RequestParam(value = "comments", required = true) String comments
	) {
		OrderInfo orderInfo = orderInfoService.get(id);
		orderInfo.setComment(comments);
		orderInfoService.update(orderInfo);
		//addLog("更新订单备注", orderInfo.toString(), "OrderInfo");
		return SUCCESS_JSON;
	}


	@RequestMapping("/getOrderDetail")
	public ModelAndView getOrderDetail(@RequestParam(value = "id", required = true) Long id) {
		ModelAndView mav = new ModelAndView("order/order/OrderDetail");
		try {
			//订单信息
			OrderInfo order = orderInfoService.get(id);
			List<Reservation> reservationList = reservationService.findByOrderId(order.getOrderNo());
			mav.addObject("order", order);
			mav.addObject("reservationList", reservationList);
		} catch (Exception ex) {
			logger.error("预约出错，", ex.getStackTrace());
		}
		return mav;
	}


	// 添加个人订单
	@RequestMapping("/toAdd")
	public ModelAndView toAdd(@RequestParam(value = "id", required = false) Long id) {
		ModelAndView mav = new ModelAndView("order/order/OrderAdd");
		try {
			if (id != null && id > 0) {
				OrderInfo order = orderInfoService.get(id);
				if (order != null) {
					mav.addObject("bean", order);
					List<Product> productList = productService.findProductByInstitutionIDAndKeywords(order.getIdInstitution(), null);
					mav.addObject("productList", productList);
				}
			}
			//机构列表
			QueryFilter filter = new DynamicSQLFilterImpl();
			filter.addFilter("Q_parentId_L_EQ", "0");
			filter.setPagingBean(null);
			List<Institution> institutionList = institutionService.find(filter);
			mav.addObject("institutionList", institutionList);
		} catch (Exception ex) {
			logger.error("添加、修改订单出错，", ex.getStackTrace());
		}
		return mav;
	}

	/**
	 * 预约/改约
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/toBespeak")
	public ModelAndView toBespeak(@RequestParam(value = "id", required = true) Long id,
								  @RequestParam(value = "yueType", required = true) Long yueType) {
		ModelAndView mav = null;
		//订单详情页
		if (yueType == 0) {
			mav = new ModelAndView("order/order/OrderDetail");
		} else if (yueType == 1) {//预约
			mav = new ModelAndView("order/order/Bespeak");
		} else if (yueType == 2) {//改约
			mav = new ModelAndView("order/order/changeBespeak");
		}
		try {
			//订单信息
			OrderInfo order = orderInfoService.get(id);
			//机构中心
			Institution institution = institutionService.get(order.getIdInstitution());
			//产品类型
			Product product = productService.get(order.getIdProduct());

			mav.addObject("institution", institution);
			mav.addObject("product", product);

			//机构列表
			QueryFilter filter = new DynamicSQLFilterImpl();
			filter.addFilter("Q_parentId_L_EQ", "0");
			filter.setPagingBean(null);
			List<Institution> institutionList = institutionService.find(filter);
			mav.addObject("institutionList", institutionList);

			List<Product> productList = productService.findProductByInstitutionIDAndKeywords(order.getIdInstitution(), null);
			mav.addObject("productList", productList);

			//改约  查询预约的对象
			if (yueType == 2) {
				Reservation reservation = reservationService.findValidByOrderId(order.getOrderNo());
				mav.addObject("reservation", reservation);
			}
			mav.addObject("order", order);
		} catch (Exception ex) {
			logger.error("预约出错，", ex.getStackTrace());
		}
		return mav;
	}

	@RequestMapping("/toExtendValidity")
	public ModelAndView toExtendValidity(@RequestParam(value = "ids", required = true) String ids) {
		ModelAndView mav = new ModelAndView("order/order/extendValidity");
		mav.addObject("ids", ids);
		return mav;
	}
	@RequestMapping("/extendValidity")
	@ResponseBody
	public Object extendValidity(@RequestParam(value = "ids", required = true) String ids,
								 @RequestParam(value = "extendDate", required = true) String extendDate,
								 HttpServletRequest request) {
		MsgBean msg = new MsgBean();
		OrderInfo ob = null;
		Date endDate = DateUtils.parseDate(extendDate);
		String[] idArr = ids.split(",");
		if (endDate != null) {
			for (String id : idArr) {
				ob = orderInfoService.get(Long.parseLong(id));
				ob.setEndDate(endDate.getTime()/1000);
				orderInfoService.update(ob);
				//addLog("订单延期", ob.toString(), "OrderInfo");
			}
		}
		return msg.returnMsg();
	}

	public String toCheck() {
		return "check";
	}

//	public void check() {
//		try {
//			List<OrderInfo> result = readOrderInfoFromXls(excel);
//			// 对账检查或者更新付款状态
//			String flag = getRequest().getParameter("flag");
//			exportCheckResult(result);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	public void exportCheckResult(List<OrderInfo> orderList, HttpServletResponse response)
			throws IOException {
		// 定义Excel的列头
		List<String> title = new ArrayList<String>();
		title.add("体检人姓名");
		title.add("年龄");
		title.add("结算价");
		title.add("订单号");
		title.add("订单中体检人");
		title.add("订单中年龄");
		title.add("订单中性别");
		title.add("订单中商家");
		title.add("订单中产品");
		title.add("订单中结算价");
		title.add("预约中体检人");
		title.add("预约中年龄");
		title.add("预约中性别");
		title.add("预约中商家");
		title.add("预约中产品");
		title.add("预约中结算价");
		title.add("订单状态");
		title.add("到检状态");
		title.add("对账结果");

		// 初始化Excel数据列表
		List<List> excelList = new ArrayList<List>();
		List<String> columns = null;
		List<OrderInfo> tmpList = null;
		List<Reservation> rtmpList = null;
		OrderInfo tmpOrder = null;
		Reservation tmpRes = null;
		boolean success = false;
		List term = null;
		QueryFilter orderFilter;
		QueryFilter reservationFilter;
		int resMatchLevel = 0;
		int orderMatchLevel = 0;
		for (OrderInfo order : orderList) {
			tmpRes = null;
			tmpOrder = null;
			success = false;
			// 初始化每一行的列数据
			columns = new ArrayList<String>();

			columns.add(order.getEndUser());
			columns.add(order.getAge().toString());
			columns.add(order.getBasePrice().toString());
			// 查询预约数据
			reservationFilter = new DynamicSQLFilterImpl();
			reservationFilter.addFilter("Q_endUser_S_EQ", order.getEndUser());
//			reservationFilter.addFilter("Q_status_S_NEQ", OrderConstants.ReservationStatus.Negative.value);
			rtmpList = reservationService.find(reservationFilter);
			if (rtmpList != null && rtmpList.size() > 0) {
				resMatchLevel = 0;
				for (Reservation r : rtmpList) {
					if (r.getStatus().equals(OrderConstants.ReservationStatus.Canceled.value)) {
						resMatchLevel = 0;
					} else {
						if (order.getAge() == r.getAge() && order.getBasePrice().intValue() == r.getBasePrice().intValue()) {
							if (resMatchLevel < 2) {
								resMatchLevel = 2;
								tmpRes = r;
								break;
							}
						} else if (order.getAge() == r.getAge()) {
							if (resMatchLevel < 1) {
								resMatchLevel = 1;
								tmpRes = r;
							}
						} else {
							tmpRes = r;
						}
					}
				}
			}
			if (tmpRes != null) {
				tmpOrder = orderInfoService.get(tmpRes.getIdOrder());
			} else {
				// 查询订单数据
				orderFilter = new DynamicSQLFilterImpl();
				orderFilter.addFilter("Q_orderStatus_S_NEQ", OrderConstants.OrderStatus.Navigate.getStatusValue());
				orderFilter.addFilter("Q_orderStatus_S_NEQ", OrderConstants.OrderStatus.Disabled.getStatusValue());
				orderFilter.addFilter("Q_orderStatus_S_NEQ", OrderConstants.OrderStatus.AgentOrder.getStatusValue());
				orderFilter.addFilter("Q_endUser_S_EQ", order.getEndUser());

				tmpList = orderInfoService.find(orderFilter);

				// 判断订单是否存在
				if (tmpList != null && !tmpList.isEmpty()) {
					orderMatchLevel = 0;
					for (OrderInfo to : tmpList) {
						if (order.getAge() == to.getAge() && order.getBasePrice().intValue() == to.getBasePrice().intValue()) {
							if (resMatchLevel < 2) {
								orderMatchLevel = 2;
								tmpOrder = to;
								break;
							}
						} else if (order.getAge() == to.getAge()) {
							if (resMatchLevel < 1) {
								orderMatchLevel = 1;
								tmpOrder = to;
							}
						} else {
							tmpOrder = to;
						}
					}
				}
			}
			if (tmpOrder != null) {
				columns.add("_" + tmpOrder.getOrderNo());
				columns.add(tmpOrder.getEndUser());
				columns.add(tmpOrder.getSex());
				columns.add(tmpOrder.getAge().toString());
				columns.add(tmpOrder.getInstitutionName() != null ? tmpOrder
						.getInstitutionName() : "");
				columns.add(tmpOrder.getProductName() != null ? tmpOrder
						.getProductName() : "");
				columns.add(tmpOrder.getBasePrice() != null ? tmpOrder
						.getBasePrice().toString() : "");
				if (tmpRes != null) {
					columns.add(tmpRes.getEndUser());
					columns.add(tmpRes.getSex());
					columns.add(tmpRes.getAge().toString());
					columns.add(tmpRes.getInstitutionName());
					columns.add(tmpRes.getProductName());
					columns.add(tmpRes.getBasePrice() != null ? tmpRes.getBasePrice().toString() : "");

				} else {
					columns.add("");
					columns.add("");
					columns.add("");
					columns.add("");
					columns.add("");
					columns.add("");
				}
				columns.add(OrderConstants.OrderStatus.getStatusName(tmpOrder.getOrderStatus()));
				if ("1".equals(tmpOrder.getIsChecked())) {
					columns.add("是");
				} else {
					columns.add("否");
				}
				success = false;
				if (tmpRes == null) {
					if (tmpOrder != null) {
						if (tmpOrder.getBasePrice() == null) {
							tmpOrder.setBasePrice(0l);
						}
						if (tmpOrder.getBasePrice().intValue() != order.getBasePrice().intValue()) {
							columns.add("结算价不同,无预约记录");
						} else if ("1".equals(tmpOrder.getPaidToInstitution())) {
							columns.add("已经付款给商家,无预约记录");
						} else {
							success = true;
							columns.add("成功,无预约记录");
						}
					} else {
						columns.add("未找到匹配记录");
					}
				} else {
					if (tmpRes.getBasePrice().intValue() != order.getBasePrice().intValue()) {
						columns.add("结算价不同");
					} else if ("1".equals(tmpOrder.getPaidToInstitution())) {
						columns.add("已经付款给商家");
					} else {
						success = true;
						columns.add("成功");
					}
				}
			} else {
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("");
				columns.add("未匹配到相应的订单");
			}

			excelList.add(columns);
		}
		// 生成Excel并返回到客户端
		response.reset();
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;Filename=Data("
				+ (new Date()).getTime() + ").xls");
		ExcelOpareUtil.write(response.getOutputStream(), title,
				excelList);

	}

	private List<OrderInfo> readOrderInfoFromXls(File fileToBeRead) {
		int result = 0;
		StringBuilder sb = new StringBuilder();
		List<OrderInfo> orderList = new ArrayList<OrderInfo>();
		OrderInfo order = null;
		try {
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
					fileToBeRead));
			HSSFSheet sheet = workbook.getSheetAt(0);
			HSSFRow row = null;
			HSSFCell cell = null;
			int rowNum, cellNum;
			rowNum = sheet.getLastRowNum();
			StringBuilder comments = new StringBuilder();
			for (int i = 1; i <= rowNum; i++) {
				order = new OrderInfo();
				row = sheet.getRow(i);
				if (row == null) {// 过滤掉Excel的空行
					continue;
				}

				cell = row.getCell((short) 0); // 体检人
				order.setEndUser(cell.toString());

				cell = row.getCell((short) 1); // 年龄
				try {
					order.setAge(Float.valueOf(cell.toString()).intValue());
				} catch (Exception e) {
					order.setAge(0);
				}

				cell = row.getCell((short) 2); // 结算价
				try {
					order.setBasePrice(Float.valueOf(cell.toString()).longValue());
				} catch (Exception e) {
					order.setBasePrice(0l);
				}
				orderList.add(order);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderList;
	}

	@RequestMapping("/updateByXls")
	public ModelAndView updateByXls(@RequestParam(value = "orderNos", required = true) String orderNos) {
		ModelAndView mav = new ModelAndView("/order/UpdateByXls");

		String[] orderNoArray = orderNos.split("\n");

		OrderInfo orderInfo = null;
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (String orderNo : orderNoArray) {
			orderNo = orderNo.trim().replace("\r", "").replace("_", "");
			orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
			sb.append(orderNo).append("\t");
			if (orderInfo != null) {
				orderInfo.setPaidToInstitution("1");
				orderInfoService.update(orderInfo);
				//addLog("更新付款状态状态", orderInfo.toString(), "OrderInfo");
				sb.append("成功");
			} else {
				sb.append("不存在");
			}
		}
		mav.addObject("orderNos", sb.toString());
		return mav;
	}

	@RequestMapping("/toUpdateByXls")
	public ModelAndView toUpdateByXls() {
		ModelAndView mav = new ModelAndView("/order/UpdateByXls");
		return mav;
	}

	@RequestMapping("/toBatchUpdatePrice")
	public ModelAndView toBatchUpdatePrice(@RequestParam(value = "ids", required = true) String ids) {
		QueryFilter qf = new DynamicSQLFilterImpl();
		qf.addFilter("Q_id_S_IN", ids);
		List<OrderInfo> orderList = orderInfoService.find(qf);
		ModelAndView mav = new ModelAndView("order/order/BatchUpdatePrice");
		mav.addObject("orderList", orderList);
		return mav;
	}

	@RequestMapping("/batchUpdatePrice")
	@ResponseBody
	public String batchUpdatePrice(@RequestParam(value = "orderInfoSize", required = true) Integer orderInfoSize,
								   HttpServletRequest request) {
		OrderInfo orderInfo = null;
		String id, salePrice, basePrice;
		for (int i = 1; i <= orderInfoSize; i++) {
			id = request.getParameter("id_" + i);
			salePrice = request.getParameter("salePrice_" + i);
			basePrice = request.getParameter("basePrice_" + i);
			orderInfo = orderInfoService.get(Long.parseLong(id));
			orderInfo.setSalePrice(Long.parseLong(salePrice));
			orderInfo.setBasePrice(Long.parseLong(basePrice));
			orderInfoService.update(orderInfo);
		}
		return SUCCESS_JSON;
	}
}
